const gulp = require('gulp');
const less = require('gulp-less');
const path = require('path');
const concat = require('gulp-concat'); // 合并
const cleanCss = require('gulp-clean-css'); // 压缩
const del = require('del'); // 删除文件
const babel = require('gulp-babel'); // es6转es5
const uglify = require('gulp-uglify'); // js压缩
const rename = require('gulp-rename'); // 文件改名
const imagemin = require('gulp-imagemin'); // 图片压缩
const spriter = require('gulp-css-spriter'); // 合成雪碧图
const base64 = require('gulp-base64'); //图片转base64
const browserSync = require('browser-sync').create(); //浏览器实时刷新
const reload = browserSync.reload;

gulp.task('html',done =>{
  console.log("html")
  done();
});

gulp.task('del',done => {
  del([
    './build/'
  ]);
  done();
})

//操作文件    gulp.src 指定文件 .pipe 下一步  gulp.dest 输出目录
gulp.task('all',done =>{
  console.log("all");
  gulp.src('./src/**/*')
    .pipe(gulp.dest('./build/'));
  done();
});
//操作文件    gulp.watch 监听文件改变
gulp.task("watchfile",done =>{
  gulp.watch("./src/index.html",done =>{
    gulp.src("./src/index.html")
      .pipe(gulp.dest("./build/"));
    done();
  });
  done();
});

gulp.task('less',done => {
  gulp.src('./src/less/*.less')
    .pipe(less())
    .pipe(concat('less.css'))
    .pipe(gulp.dest('./src/css'));
  done();
});

gulp.task('css',done => {
  gulp.src('./src/css/*.css')
    .pipe(concat('gulp.css'))
    .pipe(spriter({
      'spriteSheet': './build/img/spritesheet.png',
      'pathToSpriteSheetFromCSS': '../img/spritesheet.png'
    }))
    .pipe(cleanCss())
    .pipe(rename('./gulp.min.css'))
    .pipe(gulp.dest('./build/css'));
  done();
});

gulp.task('base64',done =>{
  gulp.src('./build/css/*.css')
    .pipe(base64())
    .pipe(gulp.dest('./build/css/'));
  done();
});

gulp.task('js',done =>{
  gulp.src('./src/js/*.js')
    .pipe(babel({
      presets: ['@babel/env']
    }))
    .pipe(concat('gulp.js'))
    .pipe(uglify())
    .pipe(rename('./gulp.min.js'))
    .pipe(gulp.dest('./src/js'));
  done();
});

gulp.task('images',done =>{
  gulp.src('./src/img/*.*')
    .pipe(imagemin())
    .pipe(gulp.dest('./build/img'));
  done();
});

// 静态服务器
gulp.task('browser-sync', function() {
  browserSync.init({
    //proxy: "你的域名或IP",
    server: {
      baseDir: "./",
      index: "./src/index.html"
    },
    port: 3000
  });

  gulp.watch("src/*.html",done =>{
    gulp.src('./src/*.html')
      .pipe(reload({
        steam: true
      }))
    done();
  });
});

gulp.task('reload',done =>{
  console.log("html")
  done();
});

gulp.task('default',gulp.series(gulp.parallel('less','css')),done =>{
  console.log('default');
  done();
});
